import React, { useState, useEffect } from 'react';
import useStore from '../../../components/useStore';
import request from '../../../untils/request';

const EditStation = () => {
    const { collapsed, setnowroute } = useStore();
    const [stationName, setStationName] = useState('');
    const [phone, setPhone] = useState('');
    const [city, setCity] = useState('');
    const [message, setMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [loading, setLoading] = useState(true);
    const [stationId, setStationId] = useState(null);

    // 从哈希路由中获取id参数
    useEffect(() => {
        const getHashParams = () => {
            // 处理哈希路由参数（#之后的部分）
            const hash = window.location.hash;
            const hashPath = hash.startsWith('#') ? hash.slice(1) : hash;
            const [, queryString] = hashPath.split('?');
            
            if (queryString) {
                const params = new URLSearchParams(queryString);
                const id = params.get('id');
                return id ? id.trim() : null;
            }
            return null;
        };

        const id = getHashParams();
        
        if (id) {
            setStationId(id);
            fetchStationInfo(id);
        } else {
            setMessage('未找到站点ID参数');
            setLoading(false);
        }
    }, [window.location.hash]);

    // 获取站点详情
    const fetchStationInfo = async (id) => {
        try {
            const res = await request("/admin/station/getStations", {
                method: "POST",
                body: {
                    id: id
                }
            });
            
            if (res.code === 200 && res.data) {
                // 从返回数据中获取站点信息
                const station = Array.isArray(res.data) ? res.data[0] : res.data;
                if (station) {
                    setStationName(station.name || '');
                    setPhone(station.phone || '');
                    setCity(station.city || '');
                } else {
                    setMessage('未找到对应站点信息');
                }
            } else {
                setMessage(res.msg || '获取站点信息失败');
            }
        } catch (error) {
            setMessage('网络错误，获取站点信息失败');
        } finally {
            setLoading(false);
        }
    };

    // 验证电话号码格式（11位数字）
    const validatePhone = (value) => {
        const reg = /^1\d{10}$/;
        return reg.test(value);
    };

    // 处理表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // 表单验证
        if (!stationName.trim()) {
            setMessage('请输入站点名称');
            return;
        }

        if (!phone.trim()) {
            setMessage('请输入负责人联系方式');
            return;
        }

        if (!validatePhone(phone.trim())) {
            setMessage('请输入有效的11位手机号码');
            return;
        }

        if (!city.trim()) {
            setMessage('请输入所在地信息');
            return;
        }
        
        try {
            setIsSubmitting(true);
            setMessage('');
            
            // 发送更新请求
            const res = await request("/admin/station/update", {
                method: "POST",
                body: {
                    id: stationId,
                    name: stationName.trim(),
                    phone: phone.trim(),
                    city: city.trim()
                }
            });
            
            if (res.code === 200) {
                setMessage('站点信息更新成功！');
            } else {
                setMessage(res.msg || '更新失败，请重试');
            }
        } catch (error) {
            setMessage('网络错误，请稍后重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    if (loading) {
        return (
            <div style={styles.loadingContainer}>
                <p>加载站点信息中...</p>
            </div>
        );
    }

    return (
        <div style={{    
            height: "94%", 
            backgroundColor: `#F1F1F1`,
            right: "1%",
            top: "4vh",
            overflow: "auto",
            width: collapsed ? "94%" : "84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={styles.header}>
                    <h2>修改站点信息</h2>
                </div>
                
                <form onSubmit={handleSubmit} style={styles.formContainer}>
                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            站点名称 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={stationName}
                            onChange={(e) => setStationName(e.target.value)}
                            style={styles.input}
                            placeholder="请输入站点名称"
                            disabled={isSubmitting}
                            maxLength={50}
                        />
                    </div>

                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            负责人联系方式 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={phone}
                            onChange={(e) => setPhone(e.target.value)}
                            style={styles.input}
                            placeholder="请输入11位手机号码"
                            disabled={isSubmitting}
                            maxLength={11}
                            // 只允许输入数字
                            onInput={(e) => e.target.value = e.target.value.replace(/[^\d]/g, '')}
                        />
                    </div>

                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            所在地 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={city}
                            onChange={(e) => setCity(e.target.value)}
                            style={styles.input}
                            placeholder="请输入所在地信息"
                            disabled={isSubmitting}
                            maxLength={50}
                        />
                    </div>
                    
                    {message && (
                        <div style={message.includes('成功') ? styles.successMsg : styles.errorMsg}>
                            {message}
                        </div>
                    )}
                    
                    <div style={styles.buttonGroup}>
                        <button 
                            type="submit" 
                            style={styles.submitBtn}
                            disabled={isSubmitting}
                        >
                            {isSubmitting ? '保存中...' : '保存'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export default EditStation

const styles = {
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", 
        top: "3%", 
        left: "1%", 
        backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)"
    },
    header: {
        padding: "1rem 2%",
        borderBottom: "1px solid #eee",
        marginBottom: "1.5rem"
    },
    formContainer: {
        width: "96%",
        margin: "0 auto",
        padding: "0 2%"
    },
    formGroup: {
        marginBottom: "1.5rem"
    },
    label: {
        display: "block",
        marginBottom: "0.5rem",
        fontSize: "0.9rem",
        color: "#333"
    },
    required: {
        color: "#ff4d4f"
    },
    input: {
        width: "100%",
        padding: "8px 12px",
        borderRadius: "4px",
        border: "1px solid #d9d9d9",
        fontSize: "0.9rem",
        boxSizing: "border-box"
    },
    successMsg: {
        color: "#52c41a",
        padding: "8px 0",
        fontSize: "0.85rem",
        marginBottom: "1rem"
    },
    errorMsg: {
        color: "#ff4d4f",
        padding: "8px 0",
        fontSize: "0.85rem",
        marginBottom: "1rem"
    },
    buttonGroup: {
        display: "flex",
        gap: "1rem",
        marginTop: "2rem"
    },
    submitBtn: {
        padding: "8px 16px",
        backgroundColor: "#1890ff",
        color: "white",
        border: "none",
        borderRadius: "4px",
        cursor: "pointer",
        fontSize: "0.9rem"
    },
    cancelBtn: {
        padding: "8px 16px",
        backgroundColor: "#f5f5f5",
        color: "#333",
        border: "1px solid #d9d9d9",
        borderRadius: "4px",
        cursor: "pointer",
        fontSize: "0.9rem"
    },
    loadingContainer: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100%",
        color: "#333",
        fontSize: "1rem"
    }
}
    